#include "element.h"
#include "factories.h"

Element::Element()
: vertexArray(NULL), verticesIndex(0), verticesSize(0), indicesIndex(0), indicesSize(0), dimmed(false)
{
}

Element::Element(const BoundingBox& boundingBox, VertexArray* vertexArray)
: boundingBox(boundingBox), vertexArray(vertexArray), verticesIndex(0), verticesSize(0), indicesIndex(0), indicesSize(0)
{
}

Element::~Element()
{
    if (vertexArray)
        delete vertexArray;
}

void Element::assign(VertexArray* destination, unsigned& verticesIndex, unsigned& indicesIndex)
{
    this->verticesIndex = verticesIndex;
    this->indicesIndex = indicesIndex;
    
    if (!vertexArray)
        return;
    
    verticesSize = vertexArray->getVerticesSize();
    indicesSize = vertexArray->getIndicesSize();
    
    if (verticesSize > 0) {
        PackedVecColor* verticesSrc = vertexArray->getVertices();
        PackedVecColor* verticesDst = destination->getVertices() + verticesIndex;
        memcpy(verticesDst, verticesSrc, verticesSize * sizeof(PackedVecColor));
        verticesIndex += verticesSize;
    }
    
    if (indicesSize > 0) {
        GLuint* indicesSrc = vertexArray->getIndices();
        GLuint* indicesDst = destination->getIndices() + indicesIndex;
        memcpy(indicesDst, indicesSrc, indicesSize * sizeof(GLuint));
        indicesIndex += indicesSize;
    }
    
    
    delete vertexArray;
    vertexArray = NULL;
}


// Event implementation

Event::Event(const QString& classDescription, const QString& typeDescription)
: classDescription(classDescription), typeDescription(typeDescription)
{
}


// State implmenetation

State::State(unsigned eventStart, unsigned eventEnd, const QString& description)
{
    SetVec3f(boundingBox.min, eventStart, -0.5, 0.0);
    SetVec3f(boundingBox.max, eventEnd, 0.5, 0.0);
	
	this->description = description;
	
    Color4b color;
	getFinalColor(color);
    setVertexArray(ObjectFactory::instance().createRectangle(boundingBox.min, boundingBox.max, color));
	
	index = eventStart;
	length = eventEnd - eventStart;
}


// Mutex implementation

Mutex::Mutex(const QString& symbol, unsigned eventStart, unsigned eventEnd, unsigned level)
: symbol(symbol)
{
	float levelHeight = (float)level;
	SetVec3f(boundingBox.min, eventStart, levelHeight - 0.5f, 0.0f);
	SetVec3f(boundingBox.max, eventEnd, levelHeight + 0.5f, 0.0f);
	
	BoundingBox renderBB = boundingBox;
	renderBB.inset(0.05, 0.05, 0.0f);
	
	Color4b color;
	getFinalColor(color);
	setVertexArray(ObjectFactory::instance().createRectangle(renderBB.min, renderBB.max, color));
	
	index = eventStart;
	length = eventEnd - eventStart;
}
